package com.gxpt.app.view;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.normal;
import com.gxpt.app.view.myview.pickerview.PickerView;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_life_service_partbid)
public class Activity_life_service_partbid extends BaseActivity {


    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.toTime1)
    RelativeLayout toTime1;

    @ViewInject(R.id.toTime2)
    RelativeLayout toTime2;


    @ViewInject(R.id.put_2)
    TextView put_2;

    @ViewInject(R.id.put_3)
    TextView put_3;

    @ViewInject(R.id.put_1)
    EditText put_1;

    @ViewInject(R.id.put_4)
    EditText put_4;


    @ViewInject(R.id.toSure)
    Button toSure;

    //timer
    Dialog dialog;
    PickerView pickerView_y,pickerView_m,pickerView_d;
    String cy=null,cm=null,cd=null;

    String ID;
    String yikoujia_is;
    float yikoujia_amount=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle b = new Bundle();
        b = getIntent().getBundleExtra("DATA");
        if(b!=null){
            ID              = b.getString("ID");
            yikoujia_is     = b.getString("yikoujia_is");
            yikoujia_amount = b.getFloat("yikoujia_amount");
        }
        x.view().inject(this);
        initView();
        initData();
    }


    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_baojia));
    }


    @Override
    public void initData() {
        if(yikoujia_is.equals("0")){
            put_1.setEnabled(false);
            put_1.setText(""+yikoujia_amount);
        }
    }



    @Event(value={R.id.toback,R.id.toTime1,R.id.toTime2,R.id.toSure})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.toTime1:
                showTimeDialog(put_2);
                break;
            case R.id.toTime2:
                showTimeDialog(put_3);
                break;
            case R.id.toSure:
                if(checkData()){
                    toNet_partbid();
                }
                break;
        }
    }

    private boolean checkData(){
        if(put_1.getText().toString().isEmpty() ||
                put_2.getText().toString().isEmpty() ||
                put_3.getText().toString().isEmpty()){
            T.show(context, getResources().getString(R.string.alert_putisnotnull), 0);
            return false;
        }
        return true;
    }


    ////////////////////////////////////////////////
    public void showTimeDialog(final TextView textview){

        dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view=LayoutInflater.from(context).inflate(R.layout.dialog_receive_time, null);
        dialog.setContentView(view);

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DATE);

        cy = ""+year;
        cm = ""+month;
        cd = ""+day;

        pickerView_y =(PickerView) view.findViewById(R.id.date_year);
        pickerView_m =(PickerView) view.findViewById(R.id.date_month);
        pickerView_d =(PickerView) view.findViewById(R.id.date_day);

//
//
        String[] date_time_y={"2017","2018","2019","2020","2021"};
        String[] date_time_m_big = { "1", "3", "5", "7", "8", "10", "12" };
        String[] date_time_m_little = { "4", "6", "9", "11" };



        final List<String> data_y=new ArrayList<String>(Arrays.asList(date_time_y));//年
        final List<String> data_m_big=new ArrayList<String>(Arrays.asList(date_time_m_big));//月
        final List<String> data_m_little=new ArrayList<String>(Arrays.asList(date_time_m_little));//月

        final List<String> data_m=new ArrayList<String>(Arrays.asList(getList(1,12)));//月



        pickerView_y.setData(data_y);
        pickerView_y.setSelected(1);

        pickerView_m.setData(data_m);
        pickerView_m.setSelected(month);



//
        if (data_m_big.contains(String.valueOf(month))) {
            pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,31))));
            pickerView_d.setSelected(day);
        } else if (data_m_little.contains(String.valueOf(month))) {
            pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,30))));
            pickerView_d.setSelected(day);
        } else {
// 闰年
            if (isLeapYear(year)){
                pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,29))));
                pickerView_d.setSelected(day);
            }else{
                pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,28))));
                pickerView_d.setSelected(day);
            }
        }

        pickerView_y.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text,int index) {
                cy = text;
                cd = "1";
                if (data_m_big.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,31))));
                    pickerView_d.setSelected(1);
                } else if (data_m_little.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,30))));
                    pickerView_d.setSelected(1);
                } else {
// 闰年
                    if (isLeapYear(Integer.parseInt(cy))){
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,29))));
                        pickerView_d.setSelected(1);
                    }else{
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,28))));
                        pickerView_d.setSelected(1);
                    }
                }
            }
        });

        pickerView_m.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text,int index) {
                cm = text;
                cd = "1";
                if (data_m_big.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,31))));
                    pickerView_d.setSelected(1);
                } else if (data_m_little.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,30))));
                    pickerView_d.setSelected(1);
                } else {
// 闰年
                    if (isLeapYear(Integer.parseInt(cy))){
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,29))));
                        pickerView_d.setSelected(1);
                    }else{
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,28))));
                        pickerView_d.setSelected(1);
                    }
                }

            }
        });
        pickerView_d.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text,int index) {
                cd = text;
            }
        });



        view.findViewById(R.id.common_cancel).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.common_sure).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                textview.setText(cy+"-"+cm+"-"+cd);
                dialog.dismiss();
            }
        });

        dialog.getWindow().setWindowAnimations(R.style.commonAnimDialogStyle);
        dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    public String[] getList(int start,int end){
        String[] a = new String[end];
        for(int n=0;n < end;n++){
            a[n] = ""+(n+1);
        }
        return a;
    }

    /**
     * 描述：判断是否是闰年()
     * <p>(year能被4整除 并且 不能被100整除) 或者 year能被400整除,则该年为闰年.
     *
     * @param year 年代（如2012）
     * @return boolean 是否为闰年
     */
    public boolean isLeapYear(int year) {
        if ((year % 4 == 0 && year % 400 != 0) || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }








    //////NET DO
    StringCallback do_partbid = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                normal data = new Gson().fromJson(s, normal.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    T.show(context,getResources().getString(R.string.alert_success_do),1);
                    EventBus.getDefault().post(new MessageEvent(Constant.ACTION_bid_success));
                    closeActivity();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

//    /////NET
    private void toNet_partbid(){
        hud.show();
          JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "bid");
            jsonBody.put("serviceName",          "partbid");

            jsonBody.put("demand_id",            ID);
            jsonBody.put("member_id",            AppUtils.get_user_id(context));
            jsonBody.put("bid_amount",           put_1.getText().toString());
            jsonBody.put("starttime",            put_2.getText().toString());
            jsonBody.put("endtime",              put_3.getText().toString());
            jsonBody.put("remark",               put_4.getText().toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+" ==["+Constant.URL_partbid+" ]");
        HttpUtils.http_post_string(Constant.URL_partbid,jsonBody.toString(),do_partbid);
    }






}
